package com.matrix.im.utils;

import com.matrix.im.config.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
/**
 * @author 有点甜
 * @since 2025/7/25
 */
@Component
@RequiredArgsConstructor
public class JwtUtil {

    private final JwtProperties jwtProperties;

    private static final String CLAIM_KEY_USER_ID = "uid";
    private static final String CLAIM_KEY_USER_ROLE = "rol";

    private Claims getClaimsFromToken(String token, String secret) {
        SecretKey key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    public Long getUserIdFromAccessToken(String token) {
        return getClaimsFromToken(token, jwtProperties.getAccessSecret()).get(CLAIM_KEY_USER_ID, Long.class);
    }

    public String getUserTypeFromAccessToken(String token) {
        return getClaimsFromToken(token, jwtProperties.getAccessSecret()).get(CLAIM_KEY_USER_ROLE, String.class);
    }

    public boolean isTokenExpired(String token) throws JwtException {
        Date expiration = getClaimsFromToken(token, jwtProperties.getAccessSecret()).getExpiration();
        return expiration.before(new Date());
    }
}
